package com.xiaoshu;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.web.filter.CharacterEncodingFilter;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.time.Duration;
import java.util.Date;

/**
 * 功能说明：
 * com.xiaoshu
 *
 * （1）actuator 微服务监控状态监控 http://127.0.0.1:8080/v1/score-server/monitor/health
 * （2）websocket 消息推送服务，推送消息到前端 http://127.0.0.1:8080/v1/score-server/page
 *
 * <p>
 * Original @Author: deane.jia-贾亮亮,2021/6/15 9:09
 * <p>
 * Copyright (C)2012-2021 小树盛凯科技 All rights reserved.
 */
@SpringBootApplication
@Slf4j
@EnableCaching
public class XiaoshuScoreServerApplication {

    public static void main(String[] args) {
        log.info("[Server Up] start up the server on time :{}", new Date());
        SpringApplication.run(XiaoshuScoreServerApplication.class, args);
    }

    /**
     * 字符拦截，使用UTF-8编码
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean<CharacterEncodingFilter> filterRegistrationBean() {
        FilterRegistrationBean<CharacterEncodingFilter> registrationBean = new FilterRegistrationBean<>();
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        registrationBean.setFilter(characterEncodingFilter);
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }

    /**
     * Redis 缓存配置，此处如果不配置，默认是选择ConcurrentHashMap作为缓存的；
     * // 设置缓存有效期1小时
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public CacheManager cacheManager(@Autowired RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1));
        return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }

}
